const db = require('../db/config');
const { sqlQueryUserTel, sqlQueryUserPwd, inserUser ,sqlUpdateUserPwd} = require('../db/accountSql');

/* 登录 */
module.exports.loginHandler = function (req, res) {
    // 后端获取前端传过来的值
    const userTel = req.body.userTel,
          userPwd = req.body.userPwd;

    //查询用户手机号是否存在
    db.query(sqlQueryUserTel, [userTel], (error, result) => {

        //手机号存在 
        if (result.length > 0) {

            db.query(sqlQueryUserPwd, [userTel, userPwd], function (err, result) {

                //手机号和密码都对
                if (result.length > 0) {
                    res.send({
                        success: true,
                        msg: '登录成功',
                        data: result[0]
                    })
                } else {
                    //密码不对
                    res.send({
                        success: false,
                        msg: '密码不正确'
                    })
                }
            })

        } else {
            // 不存在
            res.send({
                success: false,
                msg: '手机号不存在'
            })
        }

    });
}

/* 增加一个用户 */
module.exports.addUserHandler = function (req, res) {

    // 后端获取前端传过来的值
    const userTel = req.body.userTel,
        userPwd = req.body.userPwd || "666666";

    //查询用户是否存在
    db.query(sqlQueryUserTel, [userTel], (error, result) => {

        if (error) throw error;

        //用户存在
        if (result.length > 0) {
            res.send({
                isAddUser: false,
                success: true,
                msg: '登录成功',
                data: result[0]
            })
        } else {
            //用户不存在，新增一条数据
            db.query(inserUser, [userTel, userPwd], (err, result) => {

                db.query(sqlQueryUserTel, [userTel], (e, r) => {
                    res.send({
                        isAddUser: true,
                        success: true,
                        msg: '注册完成',
                        data: r[0]
                    })
                });

            });

        }

    });
}


/* 修改用户密码 */
module.exports.UpdateUserPwdHandler = function (req, res) {
    const pwd = req.body.pwd,
        id = Number(req.body.id);
    console.log(pwd,id)
    
    db.query(sqlUpdateUserPwd, [pwd, id], (error, result) => {
        if (result) {         
            res.send({
                msg: '修改密码成功'
            });            
        } else {
            res.send({
                msg: '修改密码失败'
            })
        }
    });
}

